package org.foj.presenter {

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.managers.CursorManager;
import mx.rpc.AsyncResponder;
import mx.rpc.AsyncToken;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;

import org.foj.dto.Issue;
import org.foj.event.EventDispatcherFactory;
import org.foj.event.UIEvent;
import org.foj.model.ChannelSetFactory;
import org.foj.model.IssueModel;
import org.foj.view.MasterView;

public class MasterPresenter {

  private var _view:MasterView;
  private var _issueModel:IssueModel;

  public function MasterPresenter(view:MasterView = null) {
    this._issueModel = new IssueModel();
    this._view = view;

    EventDispatcherFactory.getEventDispatcher()
        .addEventListener(UIEvent.REFRESH_ISSUES_BUTTON_CLICKED,
        getIssues);
    EventDispatcherFactory.getEventDispatcher()
        .addEventListener(UIEvent.SELECTED_ISSUE_SAVED,
        getIssues);
    EventDispatcherFactory.getEventDispatcher()
        .addEventListener(UIEvent.CANCELLED_ISSUE_EDIT,
        getIssues);
    EventDispatcherFactory.getEventDispatcher()
        .addEventListener(UIEvent.REMOVE_ISSUE_BUTTON_CLICKED,
        removeIssue);
  }

  private function getIssues(event:UIEvent = null):void {
    CursorManager.setBusyCursor();
    _issueModel.getIssues(new AsyncResponder(getIssuesResult,
        handleError));
  }

  private function removeIssue(event:UIEvent):void {
    CursorManager.setBusyCursor();
    var selectedIssue:Issue = event.data;
    _issueModel.removeIssue(selectedIssue.id,
        new AsyncResponder(removeIssueResult, handleError));
  }

  private function getIssuesResult(event:ResultEvent,
                                   token:AsyncToken = null):void {
    CursorManager.removeBusyCursor();
    var issues:ArrayCollection = new ArrayCollection();

    for each(var item:Object in event.result) {
      var issue:Issue = new Issue(item);
      issues.addItem(issue);
    }

    _view.masterViewDataGrid.dataProvider = issues;
  }

  private function removeIssueResult(event:ResultEvent,
                                     token:AsyncToken = null):void {
    CursorManager.removeBusyCursor();
    _view.masterViewDataGrid.selectedIndex = -1;
    var itemChangedEvent:UIEvent =
        new UIEvent(UIEvent.SELECTED_ISSUE_CHANGED);
    itemChangedEvent.data = new Issue();
    EventDispatcherFactory.getEventDispatcher()
        .dispatchEvent(itemChangedEvent);
    getIssues();
  }

  private function handleError(event:FaultEvent,
                               token:AsyncToken = null):void {
    CursorManager.removeBusyCursor();
    Alert.show(event.fault.faultString);
  }

}
}
